import axios from 'axios'
import { Notification } from "@douyinfe/semi-ui"
import ConstantTab from "../config/Constant";

axios.defaults.timeout = 100000;
// axios.defaults.baseURL = "http://dev.xiusin.cn";
axios.defaults.baseURL = "http://localhost:5000";

axios.interceptors.request.use(
    config => {
        const tokenJson = localStorage.getItem('token');
        if (tokenJson) {
            const tokenStr = JSON.parse(tokenJson);
            const { token, openID } = tokenStr;
            if (token && Date.now() - openID <= 3600000 * 2) {
                config.headers.Authorization = `Bearer ${token}`
            }
            else Notification.error(ConstantTab.TokenExpireNotify)
        }
        return config
    },
    error => {
        setTimeout(() => window.location.href = '/login', 1000);
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    (response) => {
        if (response.data.code === 401 || response.data.code === 500 || response.status === 500) {
            return Promise.reject(new Error(response.data.msg || '系统错误'))
        }
        return response.data;
    },
    error => Promise.reject(new Error(error.response?.data?.msg || error.message || '系统错误'))
);

class Api {
    prefix = '';

    constructor(prefix) {
        this.prefix = prefix;
    }

    getUploadUrl() {
        return axios.defaults.baseURL + '/api/common/upload'
    }

    list(data) {
        return this.post('/list', data)
    }

    delete(data) {
        return this.post('/delete', data)
    }

    save(data) {
        return this.post('/save', data)
    }

    info(data) {
        return this.post('/info', data)
    }

    get(url) {
        return axios.get(this.url(url));
    }

    post(url, data) {
        return axios.post(this.url(url), data);
    }

    url(url) {
        return this.prefix + url
    }
}

export default Api;